package com.apes.report.ext;


import com.apes.report.domain.ReportTemplate;
import com.apes.report.service.ReportProviderService;
import com.bstek.ureport.exception.ReportException;
import com.bstek.ureport.provider.report.ReportFile;
import com.bstek.ureport.provider.report.ReportProvider;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

/**
 * @author cxm
 * @since 2019年3月26日
 */
@Component
public class SqlReportProvider implements ReportProvider{
    private String prefix="oracle:";
    private boolean disabled;
    @Autowired
    ReportProviderService reportService;
    @Override
    public InputStream loadReport(String file) {
        try {
            ReportTemplate reportTemplate= reportService.selectReportTemplateByName(removePrefix(file));
            if (reportTemplate==null){
                return null;
            }else
              return IOUtils.toInputStream(reportTemplate.getContext(),"utf-8");
        } catch (Exception e) {
            throw new ReportException(e);
        }
    }

    @Override
    public void deleteReport(String file) {
        reportService.deleteReportTemplate(removePrefix(file));
    }
    
    @Override
    public List<ReportFile> getReportFiles() {
        List<ReportFile> list= new ArrayList<>();
        List<ReportTemplate> reportTemplates=reportService.getReportTemplateList();
        int iLen=reportTemplates.size();
        for(int i=0;i<iLen;i++){
            ReportTemplate reportTemplate=reportTemplates.get(i);
            System.out.println(reportTemplate.getTemplatename());
            long now = System.currentTimeMillis();
            Date CurrTime = new Date(now);
            ReportFile reportFile=new ReportFile(getPrefix()+reportTemplate.getTemplatename(),CurrTime);
            list.add(reportFile);
        }
        return list;
    }
    @Override
    public String getName() {
        return "报表模板存放到数据库";
    }

    @Override
    public void saveReport(String file,String content) {
       deleteReport(file);
       ReportTemplate  reportTemplate= new ReportTemplate();
       reportTemplate.setTemplatename(removePrefix(file));
       reportTemplate.setContext(content);
        reportService.insertReportTemplate(reportTemplate);
    }
    @Override
    public boolean disabled() {
        return disabled;
    }

    public void setDisabled(boolean disabled) {
        this.disabled = false;
    }
    @Override
    public String getPrefix() {
        return prefix;
    }

    private String removePrefix(String file){
        return file.replace("oracle:","");
    }
}